package com.swift.violent.mainstay.common.util;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * 参数转换工具
 *
 * @author xuhaifeng
 * @date 2020.2.9 上午 11:58
 */
@Slf4j
@Component
@SuppressWarnings("unused")
public class ParameterUtil {
    private static final String BRACES = "{}";
    private static final String ANNEX_BASE_64_KEY = "file";

    /**
     * 解析 FormData 参数
     * Gets parameter by form data.
     *
     * @param request the request
     *
     * @return the parameter by form data
     */
    public static JSONObject getParameterByFormData(HttpServletRequest request) {
        final JSONObject parameterObject = new JSONObject();
        final Set<Map.Entry<String, String[]>> entries = request.getParameterMap().entrySet();
        if (entries.size() != 0) {
            for (Map.Entry<String, String[]> entry : entries) {
                if (!ANNEX_BASE_64_KEY.equals(entry.getKey())) {
                    if (Objects.nonNull(entry.getValue()) && entry.getValue().length != 0) {
                        parameterObject.put(entry.getKey(), entry.getValue()[0]);
                    }
                }
            }
        }
        log.info(String.format("========================== 接收参数：\n%s", JSON.toJSONString(parameterObject)));
        return parameterObject;
    }

    /**
     * 解析 JSON 参数
     * Gets body json str by json.
     *
     * @param request the request
     *
     * @return the body json str by json
     */
    public static String getParameterByJson(HttpServletRequest request) {
        String line;
        StringBuilder json = new StringBuilder();
        try {
            BufferedReader reader = request.getReader();
            while (Objects.nonNull(line = reader.readLine())) {
                json.append(line);
            }
        } catch (Exception e) {
            log.error("请求参数转换错误!", e);
        } finally {
            if (StrUtil.isEmpty(String.valueOf(json))) {
                json = new StringBuilder().append(BRACES);
            }
        }
        final String jsonStr = String.valueOf(json);
        log.info(String.format("========================== 接收参数：\n%s", jsonStr));
        return jsonStr;
    }

}
